package model

import (
	"context"
	"time"

	"gitee.com/krio/grpc-gin-client/middleware/api"

	"gitee.com/krio/grpc-gin-client/core/lib"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	commonSdk "github.com/wangzhe1991/grpc-sdk/pb/common"
	"golang.org/x/crypto/bcrypt"

	v1 "gitee.com/krio/grpc-gin-client/dto/pb/v1"
	"gitee.com/krio/grpc-gin-client/rpc"
)

type User struct {
	SFID        string
	FirstName   string
	LastName    string
	PhoneNumber string
	Password    string
}

// LoginCheck 登录验证
func LoginCheck(ctx context.Context, req *v1.LoginReq) (bool, *User, error) {
	user, err := rpc.UserClient.Detail(ctx, &commonSdk.ID{
		Id: 1,
	})
	if err != nil {
		return false, nil, err
	}
	return true, &User{
		SFID:        string(user.Id),
		FirstName:   user.FirstName,
		LastName:    user.LastName,
		PhoneNumber: user.PhoneNumber,
		Password:    user.Password,
	}, nil
}

// GenerateToken 生成令牌
func GenerateToken(ctx *gin.Context, user *User) (*api.CustomClaims, string, error) {
	j := api.NewJWT()
	// 构造用户claims信息(负荷)
	expiresAt := time.Now().Add(time.Duration(lib.C.JWT.ExpiresTime) * time.Minute).Unix()
	claims := api.CustomClaims{
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expiresAt,        // 签名过期时间
			Issuer:    lib.C.JWT.Issuer, // 签名颁发者
			Id:        user.SFID,        // 用户ID
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		return nil, "", err
	}

	return &claims, token, nil
}

// EncryptPWD 密码加密
func EncryptPWD(pwd string) ([]byte, error) {
	return bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
}

// CheckPWD 验证密码
func CheckPWD(hashedPwd string, pwd string) error {
	return bcrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(pwd))
}
